<?php
/**
 * User: YL
 * Date: 2019/08/23
 */

namespace app\common\logic;

use think\facade\Filesystem;
use think\File;
use think\Request;
use think\Validate;

class Uploads extends Base
{
    protected $rule = [
        'file' => 'require',
    ];

    /**
     * 运行
     * @param Request $request
     * @param string $rule
     * @throws \restful\ResultException
     */
    public function run(Request $request, string $rule = '')
    {
        if ($rule) {
            $this->rule['file'] .= $rule;
        }

        $params = $request->file() ?? [];

        $validate = new Validate();
        if (! $validate->rule($this->rule)->check($params)) {
            $this->error($validate->getError());
        }

        // 上传文件
        $files = $params['file'];
        if (! is_array($files)) {
            $files = [$files];
        }

        // 储存盘
        $disk = Filesystem::disk('public');

        // 存储
        $url = [];
        foreach ($files as $file) {
            if ($file instanceof File) {
                $url[] = '/uploads/' . $disk->putFile('', $file);
            }
        }

        $this->success('文件上传成功', $url);
    }
}